package cn.zl.springbootredis.redis;

import cn.zl.springbootredis.SpringbootRedisApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @Description:
 * @Author: zhanglang
 * @Date: 2020/9/7 13:51
 */
//启动Springboot应用
@SpringBootTest(classes = SpringbootRedisApplication.class)
@RunWith(SpringRunner.class)
public class TestBoundAPI {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //Spring data 为了方便对redis进行更友好的操作，因此提供了bound api简化操作
    @Test
    public void testBound(){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        stringRedisTemplate.opsForValue().set("name","Diamond");
        stringRedisTemplate.opsForValue().append("name","你是一个好人");
        String s = stringRedisTemplate.opsForValue().get("name");
        System.out.println(s);

        //如果确认是对一个key多次操作，则对key进行绑定
        //滴哦字符串类型key进行绑定 后续所有操作都是基于这个key的操作，后续的操作参数就少了key的值
        BoundValueOperations<String, String> nameValue = stringRedisTemplate.boundValueOps("name");
        nameValue.set("Diamond");
        nameValue.append("你是一个好人");
        String s1 = nameValue.get();
        System.out.println(s1);

        //对list set zset hash

        BoundListOperations<String, String> listsValue = stringRedisTemplate.boundListOps("lists");
        listsValue.leftPushAll("张三","李四","王五");
        List<String> range = listsValue.range(0, -1);
        range.forEach( value -> System.out.println(value));

        //set
//        stringRedisTemplate.boundSetOps();
        //zset
//        stringRedisTemplate.boundZSetOps();
        //hash
//        stringRedisTemplate.boundHashOps();
        /**
         * 1.针对日后处理key value 都是String 使用StringRedisTemplate
         * 2.针对日后处理key value 存在对象 使用RedisTemplate
         * 3.针对同一个key多次操作可以使用boundXXXops()的api，简化书写
         */
    }

}
